﻿namespace KnownCMS.Services;

/// <summary>
/// 插件市场服务接口。
/// </summary>
public interface IPluginService : IService
{
    /// <summary>
    /// 异步获取推荐插件列表。
    /// </summary>
    /// <returns></returns>
    Task<List<CmPlugin>> GetRecommendPluginsAsync();

    /// <summary>
    /// 异步分页查询插件列表。
    /// </summary>
    /// <param name="criteria">查询条件。</param>
    /// <returns></returns>
    Task<PagingResult<CmPlugin>> QueryPluginsAsync(PagingCriteria criteria);

    /// <summary>
    /// 异步获取插件信息。
    /// </summary>
    /// <param name="id">插件ID。</param>
    /// <returns></returns>
    Task<CmPlugin> GetPluginAsync(string id);

    /// <summary>
    /// 异步保存插件信息。
    /// </summary>
    /// <param name="model">插件信息。</param>
    /// <returns></returns>
    Task<Result> SavePluginAsync(CmPlugin model);
}

[WebApi, Service]
class PluginService(Context context) : ServiceBase(context), IPluginService
{
    public Task<List<CmPlugin>> GetRecommendPluginsAsync()
    {
        return Database.QueryListAsync<CmPlugin>(d => d.IsRecommend);
    }

    public Task<PagingResult<CmPlugin>> QueryPluginsAsync(PagingCriteria criteria)
    {
        var sql = "select * from CmPlugin where 1=1";
        var key = criteria.Parameters.GetValue<string>("Key");
        if (!string.IsNullOrWhiteSpace(key))
        {
            var wheres = new List<string>();
            var keys = key.Split(' ');
            for (int i = 0; i < keys.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(keys[i]))
                    continue;

                wheres.Add($"Name like @Key{i}");
                wheres.Add($"Summary like @Key{i}");
                wheres.Add($"Description like @Key{i}");
                criteria.SetQuery($"Key{i}", $"%{keys[i]}%");
            }
            sql += $" and ({string.Join(" or ", wheres)})";
        }

        return Database.QueryPageAsync<CmPlugin>(sql, criteria);
    }

    public async Task<CmPlugin> GetPluginAsync(string id)
    {
        var database = Database;
        await database.OpenAsync();
        var plugin = await Database.QueryByIdAsync<CmPlugin>(id);
        if (plugin != null)
        {
            //添加查看记录，同IP记录一次
            var ip = Context.IPAddress;
            var userName = Context.CurrentUser?.UserName ?? "Anonymous";
            var isAdd = await database.AddViewLogAsync("Plugin", plugin.Id, userName, ip);
            if (isAdd)
            {
                plugin.ViewQty = (plugin.ViewQty ?? 0) + 1;
                await database.SaveAsync(plugin);
            }
        }
        await database.CloseAsync();
        return plugin;
    }

    public async Task<Result> SavePluginAsync(CmPlugin info)
    {
        if (AIHelper.HasSensitiveWords($"{info.Name},{info.Author},{info.Summary},{info.Price},{info.Description}"))
            return Result.Error("请不要在发布内容里添加敏感词！");

        if (CurrentUser.UserName != "known")
            return Result.Error("暂无权限发布插件！");

        var database = Database;
        var model = await database.QueryByIdAsync<CmPlugin>(info.Id);
        model ??= new CmPlugin();
        model.UserId = CurrentUser.Id;
        model.Status = PluginStatus.Published;
        model.Name = info.Name;
        model.Author = info.Author;
        model.Summary = info.Summary;
        model.Category = info.Category;
        model.Type = info.Type;
        model.Price = info.Price;
        model.Description = info.Description;

        var vr = model.Validate(Context);
        if (!vr.IsValid)
            return vr;

        return await database.TransactionAsync(Language.Save, async db =>
        {
            await db.SaveAsync(model);
        }, model);
    }
}